import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Icon,
  Col,
  Row,
  Input,
  InputNumber,
  Button,
  Table,
  Spin,
  Popconfirm,
  Modal,
  Switch,
} from 'antd';
import { routerRedux } from 'dva/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

@connect(({ addedServices, loading }) => ({
  ...addedServices,
  loading: loading.models.addedServices,
}))
@Form.create()
class ServiceDetail extends PureComponent {
  state = {
    currentId: null,
    productVisible: false,
    selectedRowKeys: [],
    productIsMust: 0,
  };

  columns = [
    {
      title: '商品ID',
      dataIndex: 'productId',
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
    },
    {
      title: '是否必选',
      dataIndex: 'isMust',
      render: text => (text ? '是' : '否'),
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_, record) => (
        <Popconfirm title="是否移除？" onConfirm={() => this.handleProductDelete(record.id)}>
          <a>
            <Icon type="delete" />
          </a>
        </Popconfirm>
      ),
    },
  ];

  componentWillMount() {
    const {
      products: { queryInfo },
      match: {
        params: { id },
      },
      dispatch,
    } = this.props;
    if (id && id !== 'add') {
      this.queryProductList(queryInfo);
    } else {
      dispatch({
        type: 'addedServices/clearProductList',
      });
    }
  }

  okHandle = e => {
    e.preventDefault();
    const { form, dispatch, list, current, queryInfo } = this.props;
    const { currentId } = this.state;
    const {
      match: {
        params: { id },
      },
    } = this.props;
    let tepId = currentId;
    if (id && id !== 'add') {
      tepId = id;
    }
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (err) return;
      const obj = { ...list[current], ...fieldsValue };
      if (tepId) {
        obj.id = tepId;
      }
      dispatch({
        type: 'addedServices/insertShopAdditionServices',
        payload: obj,
        callback: sid => {
          this.setState({ currentId: sid });
          dispatch({
            type: 'addedServices/selectShopAdditionalServicesList',
            payload: queryInfo,
          });
        },
      });
    });
  };

  handleProductDelete = id => {
    const {
      dispatch,
      products: { queryInfo },
    } = this.props;
    dispatch({
      type: 'addedServices/deletShopAdditionServicesProduct',
      payload: { id },
      callback: () => {
        this.setState({ productVisible: false, selectedRowKeys: [], productIsMust: 0 });
        this.queryProductList(queryInfo);
      },
    });
  };

  handleTableChange = pagination => {
    const {
      products: { queryInfo },
    } = this.props;
    const newInquiry = { ...queryInfo, pageNumber: pagination.current };
    this.queryProductList(newInquiry);
  };

  handleClickBackList = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.goBack());
  };

  handleAddProduct = () => {
    const {
      dispatch,
      match: {
        params: { id },
      },
    } = this.props;
    const { currentId } = this.state;
    this.setState({ productVisible: true });
    dispatch({
      type: 'addedServices/checkedAdditionalServicesProductList',
      payload: { pageNumber: 1, pageSize: 10, id: currentId || id, productId: null },
    });
  };

  modalProductListDom = () => {
    const { selectedRowKeys, productVisible, productIsMust } = this.state;
    const {
      goodsList: { list, queryInfo, total },
      loading,
      dispatch,
    } = this.props;

    const handleTableChange = pagination => {
      dispatch({
        type: 'addedServices/checkedAdditionalServicesProductList',
        payload: { ...queryInfo, pageNumber: pagination.current },
      });
    };

    const handleSearch = type => {
      let { searchText } = this.state;

      if (type === 'reset') {
        searchText = null;
      }
      dispatch({
        type: 'addedServices/checkedAdditionalServicesProductList',
        payload: { ...queryInfo, pageNumber: 1, productId: searchText },
      });
    };

    const onModalOk = () => {
      const {
        match: {
          params: { id },
        },
      } = this.props;
      const { currentId } = this.state;
      let tepId = currentId;
      if (id && id !== 'add') {
        tepId = id;
      }
      dispatch({
        type: 'addedServices/insertShopAdditionServicesProduct',
        payload: { isMust: productIsMust, productIds: selectedRowKeys, serviceId: tepId },
        callback: () => {
          this.setState({ productVisible: false, selectedRowKeys: [], productIsMust: 0 });
          this.queryProductList({ pageNumber: 1, pageSize: 10 });
        },
      });
    };

    const onChangeSwitch = checked => {
      this.setState({ productIsMust: checked ? 1 : 0 });
    };

    const columns = [
      {
        title: '主图',
        dataIndex: 'image',
        render: text => <img src={text} alt="" style={{ width: 60, height: 60 }} />,
      },
      {
        title: '商品Id',
        dataIndex: 'productId',
      },
      {
        title: '名称',
        dataIndex: 'name',
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: keys => {
        this.setState({ selectedRowKeys: keys });
      },
    };
    return (
      <Modal
        visible={productVisible}
        title="选择商品"
        width={750}
        onOk={onModalOk}
        onCancel={() => {
          this.setState({ productVisible: false, selectedRowKeys: [], productIsMust: 0 });
        }}
      >
        <Spin spinning={loading}>
          <div style={{ marginBottom: 20 }}>
            <Input
              style={{ width: '50%' }}
              placeholder="输入商品ID或名称进行搜索"
              onChange={e => {
                this.setState({ searchText: e.target.value });
              }}
            />
            <Button
              style={{ marginLeft: 20 }}
              type="primary"
              icon="search"
              onClick={() => handleSearch('search')}
            >
              搜索
            </Button>
            <Button style={{ marginLeft: 20 }} onClick={() => handleSearch('reset')}>
              重置
            </Button>
          </div>
          <div style={{ marginBottom: 20 }}>
            <span style={{ paddingRight: 20 }}>是否必选</span>
            <Switch checkedChildren="是" unCheckedChildren="否" onChange={onChangeSwitch} />
          </div>
          <Table
            rowKey="productId"
            rowSelection={rowSelection}
            columns={columns}
            dataSource={list}
            pagination={{
              current: queryInfo.pageNumber,
              pageSize: queryInfo.pageSize,
              total,
            }}
            onChange={handleTableChange}
          />
        </Spin>
      </Modal>
    );
  };

  queryProductList(queryInfo) {
    const { dispatch } = this.props;
    const {
      match: {
        params: { id },
      },
    } = this.props;
    const { currentId } = this.state;
    let tepId = currentId;
    if (id && id !== 'add') {
      tepId = id;
    }
    dispatch({
      type: 'addedServices/selectShopAdditionalServicesProudctList',
      payload: { ...queryInfo, id: tepId },
    });
  }

  render() {
    const {
      form: { getFieldDecorator },
      list,
      current,
      loading,
    } = this.props;
    const {
      products: { queryInfo, list: productList, total },
    } = this.props;
    const {
      match: {
        params: { id },
      },
    } = this.props;
    const { currentId } = this.state;
    return (
      <PageHeaderWrapper title="增值服务详情">
        <Spin spinning={loading}>
          <Card bordered={false} title="增值服务">
            <Form onSubmit={this.okHandle}>
              <Row gutter={16}>
                <Col lg={12} md={12} sm={24}>
                  <Form.Item label="增值服务名称">
                    {getFieldDecorator('name', {
                      initialValue: current === null ? null : list[current].name,
                      rules: [{ required: true, message: '请输入名称' }],
                    })(<Input placeholder="请输入增值服务名称" />)}
                  </Form.Item>
                </Col>
                <Col lg={12} md={12} sm={24}>
                  <Form.Item label="增值服务价格">
                    {getFieldDecorator('price', {
                      initialValue: current === null ? null : list[current].price,
                      rules: [{ required: true, message: '请输入价格' }],
                    })(<InputNumber placeholder="请输入价格" style={{ width: '100%' }} />)}
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={12} md={12} sm={24}>
                  <Form.Item label="增值服务内容">
                    {getFieldDecorator('content', {
                      initialValue: current === null ? null : list[current].content,
                      rules: [{ required: true, message: '请输入内容' }],
                    })(<Input.TextArea placeholder="请输入增值服务内容" />)}
                  </Form.Item>
                </Col>
                <Col lg={12} md={12} sm={24}>
                  <Form.Item label="增值服务说明">
                    {getFieldDecorator('description', {
                      initialValue: current === null ? null : list[current].description,
                    })(<Input.TextArea placeholder="请输入增值服务内容" />)}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Form.Item style={{ marginTop: 32 }}>
                  <Button type="primary" htmlType="submit">
                    提交
                  </Button>
                  <Button style={{ marginLeft: 8 }} onClick={this.handleClickBackList}>
                    返回
                  </Button>
                </Form.Item>
              </Row>
            </Form>
          </Card>
          <Card bordered={false} title="商品列表" style={{ marginTop: 20 }}>
            <Button
              onClick={this.handleAddProduct}
              type="primary"
              shape="round"
              style={{ marginBottom: '30px' }}
              disabled={id === 'add' && !currentId}
            >
              新增商品
            </Button>
            <Table
              columns={this.columns}
              dataSource={productList}
              pagination={{
                current: queryInfo.pageNumber,
                pageSize: queryInfo.pageSize,
                total,
              }}
              onChange={this.handleTableChange}
            />
          </Card>
          {this.modalProductListDom()}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
export default ServiceDetail;
